package net.tngou.iask.reflect;

import java.lang.reflect.InvocationTargetException;


import org.apache.commons.lang3.ArrayUtils;

import net.tngou.iask.util.StringUtil;

/**
 * 函数方法，反向代理执行
 * @author tngou@tngou.net
 *
 */
public class Method {
	private String name;
	private Object[] params = new Object[0];;
	private Class<?>[] parameterTypes=new Class[0]; ;
	public Method(String temp,Field field) {
		temp=StringUtil.replace(temp, "(", ",");
		temp=StringUtil.replace(temp, ")", ",");
		String[] temps = StringUtil.split(temp, ",");
		this.name=temps[0];
		parameterTypes=_parameterTypes(temps[0]);
		if(temps.length>1)
		{
			for (int i = 1; i < temps.length; i++) {
				params=ArrayUtils.add(params, _getValue(field,temps[i],parameterTypes[i-1]));			
			}			
		}
		
	}
	
	public Object run() {
		FilterFun fun = new FilterFun();
		try {
			return fun.getClass().getMethod(name, parameterTypes).invoke(fun, params);
		} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException
				| SecurityException e) {			
			e.printStackTrace();
			return null;
		}
	}
	/**
	 * 取得方法中的参数
	 * @param name
	 * @return
	 */
	private  Class<?>[] _parameterTypes(String name) {
	
		FilterFun fun = new FilterFun();
		java.lang.reflect.Method[] methods = fun.getClass().getDeclaredMethods();
		for (java.lang.reflect.Method m : methods) {
			if(m.getName().equals(name))
			return m.getParameterTypes();
			
		}
		return new Class[0];
	}
	
	private  Object _getValue(Field field,String name,Class<?> c ) {
		 	
		try {
			 return  field.getClass().getField(name).get(field);
		} catch (IllegalArgumentException | IllegalAccessException | NoSuchFieldException | SecurityException e) {			
			Object object=name;
			switch (c.getTypeName()) {
			case "long":
				object= Long.parseLong(name);
				break;
			case "int":
				object= Long.parseLong(name);
				break;
			default:
				break;
			}
			
			return object;
		}
		
	}
}
